(function () {
    var toolFun = function () {
        var that = this;
        this.htmlFs = document.getElementsByTagName("html")[0].style.fontSize.replace('px', '');
        //------------------------环境配置--------------------
        this.ajaxUrl = "";//ajax请求地址
        this.wapUrl = "";//warp端地址
        this.isEnvironment = 1;//以及切换环境 0测试 1正式 -1预上线
        this.openUpdate = false; //开启版本更新是IOS关闭自动更新
        this.AV = api.appVersion;//APP版本
        this.inAV = "6.1.0";//接口版本
        this.log = function (mark, logtext) {
            return;
            // if (that.isEnvironment != 0) return
            var mk = "";
            if (mark) {
                mk = mark;
            }
            if (logtext instanceof Array || logtext instanceof Object) {
                logtext = JSON.stringify(logtext);
            }
            console.log(mk + "  " + logtext);
        }
        // 服务器请求地址
        this.developmentUrl = "http://appfront.t1.anmaicloud.com/";// 测试环境
        this.preparatoryUrl = "https://preappapiv2.renrenmine.com/";//预上线环境
        this.productionUrl = "https://appapiv2-2cb021e79f60f5161dbb13a821dee32c.renrenmine.com/";
        this.warpDeveUrl = "http://ihulatu.t1.anmaicloud.com/";//warp测试
        this.warpProdurl = "https://i.hulatu.cn/";//warp正式
        // 系统类型
        this.ST = api.systemType;
        //根据环境判断地址
        function checkUrlEn(url) {
            var changeurl = {
                appUrl: "",
                warpUrl: "",
                openUpdate: false
            };
            if (url == 1) {
                changeurl.appUrl = that.productionUrl;
                changeurl.warpUrl = that.warpProdurl;
                changeurl.openUpdate = true;
            } else if (url == 0) {
                that.inAV = "5.0.0";
                changeurl.appUrl = that.developmentUrl;
                changeurl.warpUrl = that.warpDeveUrl;
            } else {
                that.inAV = "5.0.0";
                changeurl.appUrl = that.preparatoryUrl;
                changeurl.warpUrl = that.warpDeveUrl;
            }
            return changeurl
        }
        this.ajaxUrl = checkUrlEn(that.isEnvironment).appUrl;
        this.wapUrl = checkUrlEn(that.isEnvironment).warpUrl;
        this.openUpdate = false;
        //------------------------APICloud模块----------------------
        //微信分享模块
        this.wx = api.require("wxPlus");
        //微信支付模块
        this.wxPay = api.require("wxPayPlus");
        // 美洽客服模块
        this.mQia = api.require("meiQia");
        //极光推送模块
        this.jgPush = api.require('ajpush');
        // 图片浏览
        this.photoBrowser = api.require("photoBrowser");
        // 浏览器
        this.browser = api.require("webBrowser");
        // 图片裁剪
        this.clipper = api.require("FNImageClip");
        // 图片压缩
        this.filter = api.require("imageFilter");
        // 复制模块
        this.clipboard = api.require("clipBoard");
        // 文件系统木块
        this.fs = api.require("fs");
        // 轮播模块
        this.slider = api.require("UIScrollPicture");
        //手势解锁
        this.matrixLock = api.require("matrixLock");
        //极光统计
        this.ajAnalytics = api.require('ajAnalytics');
        //bug监听
        this.logCrash = api.require('logCrash');
        this.logCrash.listenCrash();
        //------------------------APP相关数据----------------------
        // 组件ID
        this.ID = "A6004740046353";
        // 设置状态栏颜色
        api.setStatusBarStyle({
            style: "dark",
            color: "rgba(0,0,0,0)"
        });
        // app名称标志
        this.FG = "wkrrm";
        // 当前显示窗口名称
        this.winName = api.pageParam.winName ? api.pageParam.winName : "index";
        this.log("init_winName", this.winName);
        // 当前frame名称
        this.frameName = api.pageParam.frameName ? api.pageParam.frameName : "";
        this.log("init_frameName", this.frameName);
        // APICloud的文件存储路径
        this.sd = api.fsDir;
        // 项目目录路径
        this.rd = api.wgtRootDir;
        this.deviceModel = api.deviceModel; //手机型号
        this.log("手机型号", this.deviceModel);
        // 页面根路径
        this.hd = api.wgtRootDir + "/html/";
        // 界面常量
        this.W = api.winWidth; // 窗口宽度
        this.H = api.winHeight; // 窗口高度
        this.FW = api.frameWidth; // frame宽度
        this.FH = api.frameHeight; // frame高度
        this.SW = api.screenHeight; //屏幕分辨率
        this.btH = 61; // 底部tab高度
        this.sH = 0;
        this.hH = 24; // 如果主界面有顶部header，那么获取其高度
        this.safetyHeaderArea = api.safeArea.top;//顶部安全距离(各种屏幕摄像头加状态栏的高度);
        this.safetyFooterArea = api.safeArea.bottom;//底部安全距离(ios各种安全距离);
        this.isHuaweip = false;
        if (this.deviceModel.indexOf("EML-AL00") != -1) {
            this.isHuaweip = true;
            this.hH = 28;
        }
        this.isHuaweip = false;
        if (this.deviceModel.indexOf("EML-AL00") != -1) {
            this.isHuaweip = true;
            this.hH = 28;
        }
        this.isiPhone10 = false; // 判断手机是不是iPhoneX/max
        if (this.deviceModel.search("iPhone") != -1 && typeof window !== 'undefined' && window) {
            var getisihone = /iphone/gi.test(window.navigator.userAgent) && window.screen.height >= 812;
            if (getisihone == true) {
                this.hH = 30; //苹果x状态栏高度为30
                this.isiPhone10 = true;
                this.btH = 80;
            }
        }
        this.showPhoneHead = true; //是否需要显示手机头部默认通知栏目
        if (this.showPhoneHead == false) {
            this.hH = 0;
        }
        this.mH = that.H - that.btH; // 主界面高度
        this.ohH = 0; // 如果其他界面有顶部header，那么获取其高度
        // 其他界面header高度
        // var otherMHH = this.getSyncStorage("OMHH");
        // if (otherMHH) {
        //     this.ohH = parseInt(otherMHH);
        // }
        this.orinDailogHH = that.ST == "ios" ? 40 : 43; // 挖矿页面时间弹窗的高度
        this.orinDailogFH = that.orinDailogHH - 1; //挖矿页面弹窗定位高度
        this.orinChooseHH = that.ST == "ios" ? 100 : 96; // 挖矿页面筛选弹窗的高度
        this.orinChooseFH = that.ST == "ios" ? that.orinChooseHH + 2 : that.orinChooseHH - 8; //挖矿页面筛选弹窗定位高度
        // 刷新页面
        this.reload = function () {
            window.location.reload();
        };
        //添加极光统计内容
        this.onEvent = function (event, dataname) {
            var param = {
                debug: true,
                crashlog: true,
                period: 0,
                channel: that.ST,
                appKey: "c2ba5a5484d5b8f3a587bf66"
            };
            // C:\Users\DELL\AppData\Roaming\360se6\Application\360se.exe
            //初始化极光统计
            that.ajAnalytics.init(param, function (ret, err) {
                that.log(JSON.stringify(ret) + JSON.stringify(err));
            })
            function _defineProperty(obj, key, value) {
                if (key in obj) {
                    Object.defineProperty(obj, key, {
                        value: value,
                        enumerable: true,
                        configurable: true,
                        writable: true
                    });
                } else {
                    obj[key] = value;
                }
                return obj;
            }
            var valueData = {
                eventType: event,
                eventId: dataname,
                attrs: _defineProperty({}, dataname, dataname)
            }
            if (event == "calculate") {
                valueData.value = 1;
            }
            that.ajAnalytics.onEvent(valueData, function (ret, err) {
                console.log(JSON.stringify(ret));
            });
        }
        // 下拉刷新
        this.downRefresh = function (callback, conf) {
            var opts = {
                visible: true,
                bgColor: "#F6F6F6",
                textColor: "#959595",
                textDown: "下拉刷新...",
                textUp: "松开刷新...",
                textLoading: "刷新中...",
                showTime: false
            };
            // 设置下拉刷新
            api.setRefreshHeaderInfo(opts, function (ret, err) {
                if (callback) {
                    callback();
                }
            });
        };
        // 打开浏览器模块
        this.browse = function (url, callback) {
            if (url && that.browser) {
                var omhh = 70; /*that.getSyncStorage("OMHH");*/
                that.browser.openView({
                    url: url,
                    rect: {
                        x: 0,
                        y: omhh,
                        w: that.W,
                        h: that.H - omhh
                    },
                    progress: {
                        color: "#45C01A",
                        height: 3
                    }
                }, function (ret, err) {
                    if (callback) {
                        callback(ret, err);
                    }
                });
            }
        };
        this.browse2 = function (url, callback) {
            if (url && that.browser) {
                var omhh = 24;
                that.browser.openView({
                    url: url,
                    rect: {
                        x: 0,
                        y: omhh,
                        w: that.W,
                        h: that.H - omhh
                    },
                    progress: {
                        color: "#181818",
                        height: 3
                    }
                }, function (ret, err) {
                    if (callback) {
                        callback(ret, err);
                    }
                });
            }
        };
        // 监听事件
        this.listen = function (event, callback) {
            if (event && typeof event == "string") {
                api.addEventListener({
                    name: event
                }, callback);
            }
            if (event instanceof Array) {
                for (var i = 0; i < event.length; i++) {
                    var e = event[i];
                    api.addEventListener({
                        name: e
                    }, callback);
                }
            }
        };
        //移除监听事件
        this.removeListen = function (event) {
            if (event && typeof event == "string") {
                api.removeEventListener({
                    name: event
                });
            }
        };
        // 监听页面滚动到底部
        this.toBottom = function (callback) {
            api.addEventListener({
                name: "scrolltobottom",
                extra: {
                    threshold: 20 //设置距离底部多少距离时触发，默认值为0，数字类型
                }
            }, function (ret, err) {
                callback(ret, err);
            });
        };
        this.upFixed = function (num, fix) {
            // num为原数字，fix是保留的小数位数
            var result = '0'
            if (Number(num) && fix > 0) { // 简单的做个判断
                fix = +fix || 2
                num = num + ''
                if (/e/.test(num)) { // 如果是包含e字符的数字直接返回
                    result = num
                } else if (!/\./.test(num)) { // 如果没有小数点
                    result = num + `.${Array(fix + 1).join('0')}`
                } else { // 如果有小数点
                    num = num + `${Array(fix + 1).join('0')}`
                    var reg = new RegExp(`-?\\d*\\.\\d{0,${fix}}`)
                    var floorStr = reg.exec(num)[0]
                    if (+floorStr >= +num) {
                        result = floorStr
                    } else {
                        var floorNumber = +floorStr + +`0.${Array(fix).join('0')}1`
                        var point = /\./.test(floorNumber + '') ? '' : '.'
                        var floorStr2 = floorNumber + point + `${Array(fix + 1).join('0')}`
                        result = reg.exec(floorStr2)[0]
                    }
                }
            }
            return result
        }
        // Android监听返回事件（目前只有android有效）
        this.back = function (callback) {
            api.addEventListener({
                name: "keyback"
            }, function (ret, err) {
                that.log("back", "监听到android返回键事件" + JSON.stringify(ret) + JSON.stringify(err));
                if (callback) {
                    callback(ret, err);
                }
            });
        };
        // 关闭当前frame
        this.closeF = function (name) {
            if (!name) {
                api.closeFrame();
            } else {
                api.closeFrame({
                    name: name
                });
            }
        };
        // 把字符串转为数字（整数和浮点数）
        this.toNum = function (num) {
            var result;
            if (num) {
                if (typeof num == "string") {
                    result = Number(num);
                }
                if (typeof num == "number") {
                    result = num;
                }
            }
            return result;
        };
        // android和ios监听app退到后台
        this.pause = function (callback) {
            api.addEventListener({
                name: "pause"
            }, function (ret, err) {
                that.log("pause", ret);
                callback(ret, err);
            });
        };
        // 触发事件
        this.trigger = function (event, data) {
            if (event) {
                api.sendEvent({
                    name: event,
                    extra: data
                });
            }
        };
        // android和ios监听app进入前台
        this.resume = function (callback) {
            api.addEventListener({
                name: "resume"
            }, function (ret, err) {
                //that.trigger("reset_tabs");
                //that.log("resume", ret);
                callback(ret, err);
            });
        };
        //时间函数 返回现在日期加上指定天数后的日期
        this.showdate = function (n) {
            var uom = new Date(new Date() - 0 + n * 86400000);
            var month = uom.getMonth() + 1 < 10 ? "0" + (uom.getMonth() + 1) : uom.getMonth() + 1;
            var days = uom.getDate() < 10 ? "0" + uom.getDate() : uom.getDate();
            var time = " 00:00:00";
            uom = uom.getFullYear() + "-" + month + "-" + days + time;
            return uom;
        };
        //把传入页面提到最前面显示
        this.toFront = function (from, to, time) {
            var conf = {
                from: from
            };
            if (to) {
                conf.to = to;
            }
            var waitTime2 = 100;
            if (time) {
                waitTime2 = time;
            }
            setTimeout(function () {
                api.bringFrameToFront(conf);
            }, waitTime2);
        };
        this.getTargetnew = function (urlPage) {
            var url = urlPage.replace('//?', '?').replace('//', '?');
            url = url.split("?")[1];
            var arr = url.split("&");
            var obj = {};
            for (var i = 0; i < arr.length; i++) {
                var objname = arr[i].split("=")[0];
                obj[objname] = arr[i].split("=")[1];
            }
            return obj;
        }
        // 提示
        this.toast = function (msg) {
            var msgLength = msg.length;
            that.openFrame({
                name: "toastDialog",
                url: that.hd + "toolhtml/toast.html",
                bgColor: "rgba(0,0,0,0.7)",
                rect: {
                    x: that.W * 0.1,
                    y: that.H * 0.45,
                    w: that.W - (that.W * 0.2),
                    h: msgLength > 50 ? 80 : 50,
                },
                pageParam: {
                    msg: msg
                }
            });
        };
        this.togClass = function (clickEle, claz, targetEle, callback) {
            if (clickEle && claz) {
                if ($) {
                    $(clickEle).click(function () {
                        var ftarget = clickEle;
                        if (targetEle) {
                            ftarget = clickEle + " " + targetEle;
                            $(ftarget).removeClass(claz);
                            $(this).find(targetEle).addClass(claz);
                        } else {
                            $(ftarget).removeClass(claz);
                            $(this).addClass(claz);
                        }
                        if (callback) {
                            callback();
                        }
                    });
                } else {
                    that.log("togClass", "依赖jquery");
                }
            }
        };
        // 提示（延时）
        this.toastDefi = function (msg, time) {
            var minTime = 2000;
            if (minTime <= time) {
                minTime = time;
            }
            api.toast({
                msg: msg,
                location: "middle",
                duration: minTime,
                global: true
            });
        };

        // 设置偏好设置
        this.setStorage = function (key, value) {
            var val = value;
            if (key) {
                if (val instanceof Object || val instanceof Array) {
                    val = JSON.stringify(val);
                }
                api.setPrefs({
                    key: key,
                    value: val
                });
            }
        };
        // 同步读取偏好设置
        this.getSyncStorage = function (key) {
            if (key) {
                var value = api.getPrefs({
                    sync: true,
                    key: key
                });
                return value;
            } else {
                return null;
            }
        };
        // 定时任务
        this.tout = function (milli, callback) {
            if (milli) {
                setTimeout(callback, milli);
            }
        };
        //金额格式化
        this.outputmoney = function (value) {
            var result = "";
            //将整数部分和小数部分分开
            var valueParts = String(value).split(".");
            var mostSignificationDigit = valueParts[0].length - 1; // 最高有效数字位，默认为个位
            var intervalOfDigit = 0; // 逗号之间的位数（从零累计）
            var digit, countOfSignificationDigit;

            //按位取出整数部分的值
            //如果不加下面这句话，低版本浏览器可能无法处理整数部分
            var roundNum = valueParts[0].split("");
            for (var i = valueParts[0].length - 1; i >= 0; i--) {
                digit = roundNum[i];
                result = digit + result;
                if (digit != "0") {
                    mostSignificationDigit = i;
                }
                //每三位添加逗号
                if (3 == ++intervalOfDigit) {
                    result = "," + result;
                    intervalOfDigit = 0;
                }
            }
            if (mostSignificationDigit == -1) {
                result = "0";
            } else {
                countOfSignificationDigit =
                    valueParts[0].length - mostSignificationDigit;
                if (countOfSignificationDigit > 3) {
                    result = result.substring(
                        result.length -
                        (countOfSignificationDigit % 3 == 0 ?
                            countOfSignificationDigit / 3 - 1 :
                            countOfSignificationDigit / 3) -
                        countOfSignificationDigit);
                } else {
                    result = result.substring(result.length - countOfSignificationDigit);
                }
            }
            if (valueParts.length == 2) {
                result += ".";
                var temp = 2 - valueParts[1].length; // 是否需要补0
                for (var i = 0; i < temp; i++) {
                    valueParts[1] += "0";
                }
                result += valueParts[1].substring(0, 2);
            } else {
                result += ".00";
            }
            return result;
        };
        //金额后保留两位小数
        this.changeTwoDecimal_f = function (x) {
            var f_x = parseFloat(x);
            if (isNaN(f_x)) {
                alert('function:changeTwoDecimal->parameter error');
                return false;
            }
            var f_x = Math.round(x * 100) / 100;
            var s_x = f_x.toString();
            var pos_decimal = s_x.indexOf('.');
            if (pos_decimal < 0) {
                pos_decimal = s_x.length;
                s_x += '.';
            }
            while (s_x.length <= pos_decimal + 2) {
                s_x += '0';
            }
            return s_x;
        }
        // 乘法高精度算法
        this.accMul = function (arg1, arg2, lineNum) {
            if (lineNum) {
                that.log("调用行数////////////" + lineNum);
            }
            var m = 0,
                s1 = arg1.toString(),
                s2 = arg2.toString();
            try {
                m += s1.split(".")[1].length;
            } catch (e) { }
            try {
                m += s2.split(".")[1].length;
            } catch (e) { }
            return (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) / Math.pow(10, m);
        };
        // 多个数字乘法高精度算法
        this.accMoreMul = function () {
            var a = 1;//初始化数据
            for (var i in arguments) {
                a = that.accMul(a, arguments[i]);
            }
            return a
        }

        // 多个数字减法高精度算法
        this.accMoreSub = function () {
            var a = arguments[0];//初始化数据
            for (var i = 1; i < arguments.length; i++) {
                a = that.numSub(a, arguments[i]);
            }
            return a
        }
        // 加法高精度算法
        this.accAdd = function (arg1, arg2) {
            var r1, r2, m, n;
            try {
                r1 = arg1.toString().split(".")[1].length;
            } catch (e) {
                r1 = 0;
            }
            try {
                r2 = arg2.toString().split(".")[1].length;
            } catch (e) {
                r2 = 0;
            }
            m = Math.pow(10, Math.max(r1, r2));
            n = r1 >= r2 ? r1 : r2;
            return that.sliceNum(((that.accMul(arg1, m) + that.accMul(arg2, m)) / m), n);
        };

        //多个数字高精度加法算法
        this.moreAccAdd = function () {
            var arg1 = 0, arg2, args = arguments, r1, r2, m, n;
            while (args.length) {
                arg2 = args[0];
                try {
                    r1 = arg1.toString().split(".")[1].length;
                } catch (error) {
                    r1 = 0;
                }
                try {
                    r2 = arg2.toString().split(".")[1].length;
                } catch (error) {
                    r2 = 0;
                }
                m = Math.pow(10, Math.max(r1, r2));
                n = r1 >= r2 ? r1 : r2;
                [].shift.call(args, 1);
                arg1 = ((arg1 * m + arg2 * m) / m).toFixed(n);
            }
            return arg1;
        };
        //减法
        this.numSub = function (num1, num2) {
            var baseNum, baseNum1, baseNum2;
            var precision; // 精度
            try {
                baseNum1 = num1.toString().split(".")[1].length;
            } catch (e) {
                baseNum1 = 0;
            }
            try {
                baseNum2 = num2.toString().split(".")[1].length;
            } catch (e) {
                baseNum2 = 0;
            }
            baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
            precision = baseNum1 >= baseNum2 ? baseNum1 : baseNum2;
            return that.sliceNum(((that.accMul(num1, baseNum) - that.accMul(num2, baseNum)) / baseNum), precision);
        };
        // 心跳任务
        this.theart = function (milli, callback) {
            if (milli) {
                var index = setInterval(callback, milli);
                this.theart.stop = function () {
                    window.clearInterval(index);
                };
            }
        };
        //高精度除法
        this.accDiv = function (num1, num2) {
            var t1, t2, r1, r2;
            try {
                t1 = num1.toString().split(".")[1].length;
            } catch (e) {
                t1 = 0;
            }
            try {
                t2 = num2.toString().split(".")[1].length;
            } catch (e) {
                t2 = 0;
            }
            r1 = Number(num1.toString().replace(".", ""));
            r2 = Number(num2.toString().replace(".", ""));
            return (r1 / r2) * Math.pow(10, t2 - t1);
        };
        // for循环（循环对象或者数组）
        this.for = function (target, callback) {
            if (target instanceof Array) {
                for (var i = 0; i < target.length; i++) {
                    var index2 = i;
                    that.log("index2", index2);
                    var ret = {};
                    ret.target = target;
                    ret.item = target[index2];
                    ret.index = index2;
                    callback(ret);
                }
                return;
            }
            if (target instanceof Object) {
                for (var key in target) {
                    var key2 = key;
                    var ret = {};
                    ret.target = target;
                    ret.item = target[key2];
                    ret.key = key2;
                    callback(ret);
                }
            }
        };
        // 获取协议
        this.getProtocol = function (url) {
            var result = null;
            if (url) {
                var splits = url.split(":");
                result = splits[0];
            }
            return result;
        };
        // 统一APP入口创建win
        this.openWin = function (config) {
            that.log("页面路径", config.url);
            if (config instanceof Object) {
                // 保存当前窗口名称到本地数据库
                that.setStorage("curWin", config.name);
                api.openWin(config);
            }
        };
        // 跳转到登录页
        this.goLogin = function (isTrigger) {
            that.tout(200, function () {
                api.openWin({
                    name: "login_reg",
                    url: api.wgtRootDir + "/html/login/login_reg.html",
                    allowEdit: true,
                    pageParam: {
                        isTrigger: isTrigger || ""
                    }
                });
            });
            that.setStorage("curWin", "login_reg");
        };
        // 转菊花
        this.flower = function (param) {
            that.toFront("flower");
            api.openFrame({
                name: "flower",
                url: that.hd + "toolhtml/flower.html",
                pageParam: param,
                bgColor: ""
            });
            this.flower.close = function () {
                api.closeFrame({
                    name: "flower"
                });
            };
        };
        //打开菊花页面
        this.openFlower = function (param) {
            api.openFrame({
                name: "flower",
                url: that.hd + "toolhtml/flower.html",
                pageParam: param,
                bgColor: ""
            });
            that.toFront("flower");
        };
        // 关闭菊花
        this.closeFlower = function (time) {
            // 延时关闭
            setTimeout(function () {
                api.closeFrame({
                    name: "flower"
                });
            }, time ? time : 1000);
        };
        //打开算力竞猜菊花页面
        this.competitionFlower = function (param) {
            api.openFrame({
                name: "competitionFlower",
                url: that.hd + "toolhtml/competition_flower.html",
                pageParam: param,
                bgColor: ""
            });
            that.toFront("competitionFlower");
        };
        // 关闭菊花
        this.closeCompetition = function (time) {
            // 延时关闭
            setTimeout(function () {
                api.closeFrame({
                    name: "competitionFlower"
                });
            }, time ? time : 1000);
        };
        // 下拉刷新结束下拉
        this.stopRefresh = function () {
            api.refreshHeaderLoadDone();
        };
        this.download2 = function (url, name, callback) {
            if (url) {
                var arr = url.split("/");
                var fileName = arr[arr.length - 1];
                var fileFix = fileName.split(".")[1];
                if (name) {
                    fileName = name;
                }
                api.download({
                    url: url,
                    savePath: "fs://renDown/" + fileName + ".jpg",
                    report: true,
                    cache: true,
                    allowResume: true
                }, function (ret, err) {
                    if (ret.state != 1) {
                        if (ret.state == 2) {
                            that.log("download", "下载文件失败：" + url);
                        } else {
                            that.log("download", "文件下载中");
                        }
                    }
                    if (callback) {
                        callback(ret, err);
                    }
                });
            }
        };
        //清楚储存在本地的账号
        this.delAccount = function () {
            that.setAccount("");
            that.setAccount(that.userfirstSet);
        }
        //储存bhpay关联信息
        this.bhpayIsLine = function (itemacc) {
            var isBingPhpay = this.parse(this.getSyncStorage("bindPhpay"));
            if (!isBingPhpay) {
                this.setStorage("bindPhpay", "false");
            }
            if (itemacc && itemacc == "true") {
                this.setStorage("bindPhpay", "true");
            }
            if (itemacc && itemacc == "false") {
                this.setStorage("bindPhpay", "false");
            }
            return this.getSyncStorage("bindPhpay")
        }
        //储存是否打开分期购信息
        this.fenQiBuy = function (itemacc) {
            var isBingPhpay = this.parse(this.getSyncStorage("isOpenFenQiBuy"));
            if (!isBingPhpay) {
                this.setStorage("isOpenFenQiBuy", "false");
            }
            if (itemacc && itemacc == "true") {
                this.setStorage("isOpenFenQiBuy", "true");
            }
            if (itemacc && itemacc == "false") {
                this.setStorage("isOpenFenQiBuy", "false");
            }
            return this.getSyncStorage("isOpenFenQiBuy")
        }
        // 公用ajax，主要是统一解决用户未登录，跳转登录页（主要用于非文件请求）
        this.ajax = function (conf) {
            // 请求状态码
            var needLogin = -100;//需要登录
            that.log("查看请求数据", JSON.stringify(conf));
            conf.param.data.values['version'] = that.inAV;
            // 列表状态文本
            var NOMORE = "没有更多数据了";
            var LOADMORE = "上拉加载更多";
            var LOADING = "加载中...";
            var NETERR = "加载中...";
            var errArr = ["连接错误", "网络超时", "授权错误", "数据类型错误", "不安全的数据"];
            if (conf && conf instanceof Object) {
                // 如果是列表加载，并且列表正处于加载状态，退出
                if (conf.extra && conf.extra.container && that.listAjaxing) {
                    return;
                }
                // 如果是普通加载
                if (!conf.extra || !conf.extra.container) {
                    that.listAjaxing = false;
                }
                // 如果是列表加载，并且列表没有处于加载状态，执行加载
                if (conf.extra && conf.extra.container && !that.listAjaxing) {
                    that.listAjaxing = true;
                    // 判断通过，显示正在加载中...
                    $("#listState").text(LOADING);
                }
                // 开始转菊花
                if (conf.extra && conf.extra.isflower) {
                    if (conf.extra.flowerParam) {
                        that.flower(conf.extra.flowerParam);
                    } else {
                        that.flower();
                    }
                }
                if (that.connectionType == "none") {
                    that.toast("请打开网络链接");
                    that.closeFlower();
                    return
                }
                var ajaxParam = conf.param;
                var ajaxId = "id" + Math.ceil(Math.random() * 10) * 10; //ajaxId;
                ajaxParam['tag'] = ajaxId;
                conf.param.timeout = 30;
                console.log("请求参数" + JSON.stringify(conf.param));
                api.ajax(conf.param, function (ret, err) {
                    // 不管是普通还是列表加载，加载完成后，都重置listAjaxing为false
                    that.listAjaxing = false;
                    // 关闭菊花
                    if (conf.extra && conf.extra.isflower) {
                        if (that.flower.close) {
                            if (conf.extra.delay) {
                                that.tout(conf.extra.delay, function () {
                                    that.flower.close();
                                });
                            } else {
                                that.flower.close();
                            }
                        }
                        if (conf.extra.flowerParam && conf.extra.flowerParam.delay) {
                            that.tout(conf.extra.flowerParam.delay + 800, function () {
                                that.flower.close();
                            });
                        }
                    }
                    if (ret) {
                        if (ret.code == 443) {
                            //登录信息验证错误,跳登录页面
                            that.log("needLogin13", needLogin);
                            that.stopRefresh();// 如果在下拉刷新，停止
                            that.closeF("rhead");
                            var matrixLock = api.require("matrixLock");
                            var accountSet = that.getAccountSet();
                            that.openHandPassword = false;
                            that.setAccount(accountSet);
                            matrixLock.clearGesture();
                            that.bhpayIsLine("false");
                            that.fenQiBuy("false");
                            // 跳转到登录界面
                            that.goLogin();
                            that.trigger("quit_login");
                            that.setStorage("readArgment", "false");
                            that.delAccount();
                            return;
                        } else if (ret.code == -510) {
                            that.toast(ret.message);
                        } else if (ret.code == 505) {
                            //停服
                            api.openWin({
                                name: "upDataPage",
                                url: api.wgtRootDir + "/html/toolhtml/stopserving.html",
                                pageParam: {
                                    pageValue: ret.data.notice
                                }
                            });
                        } else {
                            // 判断是否是列表请求
                            if (ret.current_page && ret.total_page) {
                                // 判断是否还有下一页
                                if (
                                    parseInt("" + ret.current_page) == parseInt("" + ret.total_page)) {
                                    // 显示没有更多数据了
                                    if (conf.extra && conf.extra.container) {
                                        $("#listState").text(NOMORE);
                                    }
                                } else {
                                    // 显示上拉加载下一页
                                    if (conf.extra && conf.extra.container) {
                                        $("#listState").text(LOADMORE);
                                    }
                                }
                            }
                            // 先调回调，比如渲染模板之类的......
                            if (conf.param.callback) {
                                conf.param.callback(ret, err);
                            }
                            // 为页面跳转添加点击
                            that.handlePage();
                        }
                    } else if (err) {
                        that.stopRefresh();
                        if (conf.extra && conf.extra.container) {
                            $("#listState").text(NETERR);
                        }
                        console.log('err' + JSON.stringify(err));
                        that.log("ajax错误" + errArr[err.code]);
                        that.log("ajax错误", err)
                        that.toast(errArr[err.code]);
                        api.cancelAjax({
                            tag: ajaxId
                        });
                        that.closeFlower();
                        if (conf.param.failed) {
                            conf.param.failed();
                        }
                    } else {
                        that.stopRefresh();
                        if (conf.extra && conf.extra.container) {
                            $("#listState").text(NETERR);
                        }
                        that.toast("网络链接失败!");
                        api.closeFrame({
                            name: "flower"
                        });
                        if (conf.param.failed) {
                            conf.param.failed();
                        }
                    }
                });
            }
        };
        //请求短信验证码(不需要登录)
        this.getSmsNologin = function (data, callback) {
            that.openFlower();
            data.version = that.inAV;
            api.ajax({
                url: that.ajaxUrl + "smscaptcha/get",
                method: 'post',
                timeout: 30,
                data: {
                    values: data
                }
            }, function (ret, err) {
                that.closeFlower();
                if (err) {
                    var errArr = ["连接错误", "网络超时", "授权错误", "数据类型错误", "不安全的数据"];
                    that.toast(errArr[err.code]);
                    return
                }
                if (ret) {
                    callback(ret);
                } else {
                    that.toast("网络链接失败!");
                };
            });
        };
        //首页以及市场页面是否需要开启BHPay验证
        this.appOpen = function (callback) {
            that.openFlower();
            api.ajax({
                url: that.ajaxUrl + "site/open",
                method: 'post',
                timeout: 30,
                data: {
                    values: {
                        token: that.getAccountSet().token,
                        deviceModel: that.deviceModel,
                        system: that.ST,
                        version: that.inAV
                    }
                }
            }, function (ret, err) {
                that.closeFlower();
                that.log("---------", ret)
                if (err) {
                    var errArr = ["连接错误", "网络超时", "授权错误", "数据类型错误", "不安全的数据"];
                    that.toast(errArr[err.code]);
                    return
                }
                if (ret) {
                    callback(ret);
                } else {
                    that.toast("网络链接失败!");
                };
            });
        };
        // 读取存在本地的首页弹框
        this.ischeckRead = function () {
            var val = that.getSyncStorage("isRead");
            if (!val) {
                val = [];
                that.setStorage("isRead", "[]");
            }
            if (Array.isArray(val)) {
                val = JSON.parse(val);
            }
            return JSON.parse(val);
        };
        // 关闭组件（静默关闭）
        this.closeAPP = function () {
            api.closeWidget({
                id: that.ID,
                retData: {
                    name: 'closeWidget'
                },
                silent: true,
                animation: {
                    type: 'flip',
                    subType: 'from_bottom',
                    duration: 500
                }
            });
        };
        // 安装应用
        this.install = function (path) {
            if (path) {
                api.installApp({
                    appUri: path
                });
            }
        };
        //不需要登录
        this.getSmsNologin = function (data, callback) {
            that.openFlower();
            data.version = that.inAV;
            api.ajax({
                url: that.ajaxUrl + "smscaptcha/get",
                method: 'post',
                timeout: 30,
                data: {
                    values: data
                }
            }, function (ret, err) {
                that.closeFlower();
                if (err) {
                    var errArr = ["连接错误", "网络超时", "授权错误", "数据类型错误", "不安全的数据"];
                    that.toast(errArr[err.code]);
                    return
                }
                if (ret) {
                    callback(ret);
                } else {
                    that.toast("网络链接失败!");
                };
            });
        };
        //请求短信验证码(需要登录)
        this.getSmslogin = function (data, callback) {
            that.openFlower();
            data.token = that.getAccount().token;
            data.version = that.inAV;
            api.ajax({
                url: that.ajaxUrl + "smscaptcha/post",
                method: 'post',
                timeout: 30,
                data: {
                    values: data
                }
            }, function (ret, err) {
                that.closeFlower();
                if (err) {
                    var errArr = ["连接错误", "网络超时", "授权错误", "数据类型错误", "不安全的数据"];
                    that.toast(errArr[err.code]);
                    return
                }
                if (ret) {
                    callback(ret);
                } else {
                    that.toast("网络链接失败!");
                };
            });
        }
        //请求普通数据
        this.ajaxPro = function (parameter, callback) {
            if (parameter.openFlower && parameter.openFlower == true) {
                that.openFlower();
            }
            parameter.values.version = that.inAV;
            that.log("接口请求参数", that.ajaxUrl + parameter.url + JSON.stringify(parameter.values));
            api.ajax({
                url: that.ajaxUrl + parameter.url,
                method: 'post',
                timeout: 30,
                data: {
                    values: parameter.values
                },
            }, function (ret, err) {
                that.stopRefresh();
                if (parameter.openFlower && parameter.openFlower == true) {
                    that.closeFlower();
                }
                that.log("接口请求返回ret---------------", that.ajaxUrl + parameter.url + JSON.stringify(ret));
                // that.log("接口请求返回err---------------", that.ajaxUrl + parameter.url + JSON.stringify(err));
                //ajax错误
                if (err) {
                    var errArr = ["连接错误", "网络超时", "授权错误", "数据类型错误", "不安全的数据"];
                    that.toast(errArr[err.code]);
                    that.log("接口请求返回err---------------", that.ajaxUrl + parameter.url + JSON.stringify(err));
                    return
                }
                if (ret.code == 443) {
                    that.stopRefresh();// 如果在下拉刷新，停止
                    that.closeF("rhead");
                    var matrixLock = api.require("matrixLock");
                    var accountSet = that.getAccountSet();
                    that.openHandPassword = false;
                    that.setAccount(accountSet);
                    matrixLock.clearGesture();
                    that.toast("请重新登录");
                    // 跳转到登录界面
                    that.goLogin();
                    that.bhpayIsLine("false");
                    that.fenQiBuy("false");
                    that.setStorage("readArgment", "false");
                    that.delAccount();
                    that.trigger("quit_login");
                    return
                }
                if (ret.code == 505) {
                    api.openWin({
                        name: "upDataPage",
                        url: api.wgtRootDir + "/html/toolhtml/stopserving.html",
                        pageParam: {
                            pageValue: ret.data.notice
                        }
                    });
                    return
                }
                if (ret) {
                    callback(ret)
                } else {
                    that.toast("网络链接失败!");
                }
            })
        }

        //请求外部普通数据
        this.ajaxProOutLine = function (parameter, callback) {
            if (parameter.openFlower && parameter.openFlower == true) {
                that.openFlower();
            }
            parameter.values.version = that.inAV;
            that.log("接口请求参数", parameter.url + JSON.stringify(parameter.values));
            api.ajax({
                url: parameter.url,
                method: parameter.method,
                timeout: 30,
                data: {
                    values: parameter.values
                },
            }, function (ret, err) {
                that.stopRefresh();
                if (parameter.openFlower && parameter.openFlower == true) {
                    that.closeFlower();
                }
                that.log("接口请求返回ret---------------", parameter.url + JSON.stringify(ret));
                // that.log("接口请求返回err---------------", that.ajaxUrl + parameter.url + JSON.stringify(err));
                //ajax错误
                if (err) {
                    var errArr = ["连接错误", "网络超时", "授权错误", "数据类型错误", "不安全的数据"];
                    that.toast(errArr[err.code]);
                    that.log("接口请求返回err---------------", parameter.url + JSON.stringify(err));
                    return
                }
                if (ret.code == 443) {
                    that.stopRefresh();// 如果在下拉刷新，停止
                    that.closeF("rhead");
                    var matrixLock = api.require("matrixLock");
                    var accountSet = that.getAccountSet();
                    that.openHandPassword = false;
                    that.setAccount(accountSet);
                    matrixLock.clearGesture();
                    that.toast("请重新登录");
                    // 跳转到登录界面
                    that.goLogin();
                    that.bhpayIsLine("false");
                    that.fenQiBuy("false");
                    that.setStorage("readArgment", "false");
                    that.delAccount();
                    that.trigger("quit_login");
                    return
                }
                if (ret.code == 505) {
                    api.openWin({
                        name: "upDataPage",
                        url: api.wgtRootDir + "/html/toolhtml/stopserving.html",
                        pageParam: {
                            pageValue: ret.data.notice
                        }
                    });
                    return
                }
                if (ret) {
                    callback(ret)
                } else {
                    that.toast("网络链接失败!");
                }
            })
        }
        //是否需要人机验证
        this.checkIsMechine = function (type, callback) {
            // rent租用，login 登录注册，sms短信
            that.ajaxPro({
                url: "site/yzm",
                values: {
                    type: type
                },
                openFlower: true
            }, function (ret) {
                if (ret) {
                    // "data": 1//1需要 0不需要
                    callback(ret);
                } else {
                    that.toast(ret.message)
                }
            })
        }
        //异步ajax
        this.asynchronousAjax = function (url, parameter, callback) {
            // that.log("异步请求借口数据", that.ajaxUrl + url + JSON.stringify(parameter));
            function getData(url, parameter) {
                parameter.version = that.inAV;
                return new Promise(function (resolve, reject) {
                    api.ajax({
                        url: that.ajaxUrl + url,
                        method: 'post',
                        data: {
                            values: parameter
                        }
                    }, function (ret, err) {
                        that.log("异步接口请求返回---------------" + that.ajaxUrl + url + "  " + JSON.stringify(ret));
                        if (ret) {
                            resolve(ret);
                        } else {
                            console.log(err);
                            var errArr = ["连接错误", "网络超时", "授权错误", "数据类型错误", "不安全的数据"];
                            that.log(errArr[err.code]);
                            reject(err);
                        }
                    });
                })
            }
            getData(url, parameter).then(function (ret) {
                callback(ret);
            }).catch(function (ret) {
                callback(ret);
            })
        }
        //新封装ajax
        this.ajaxNew = function (url, parameter, openFlower, callback) {
            // that.log("请求参数==========", "url:" + that.ajaxUrl + url + "----------parameter:" + JSON.stringify(parameter) + "-------openFlower:" + openFlower);
            var errArr = ["连接错误", "网络超时", "授权错误", "数据类型错误", "不安全的数据"];
            if (openFlower && openFlower) {
                that.flower();
            }
            api.ajax({
                url: that.ajaxUrl + url,
                method: 'post',
                timeout: 30,
                data: {
                    values: parameter
                },
            }, function (ret, err) {
                that.stopRefresh();
                if (openFlower && openFlower) {
                    that.closeFlower();
                }
                that.log("接口请求返回---------------", that.ajaxUrl + url + JSON.stringify(ret));
                if (ret) {
                    callback(ret)
                } else {
                    that.toast("网络链接失败!");
                }
                if (err) {
                    that.toast(errArr[err.code]);
                }
            })
        };
        //用户初始默认值
        this.userfirstSet = {
            //资产统计初始化数据
            checkMyProperty: {
                isMyblance: "false",
                isMyCoin: "false",
                isMyEchem: "false",
                isOtcCoin: "false"
            },
            dataStaus: "true", //默认显示账户总资产
            openHandPassLine: "true", //默认打开手势连线
            openHandPassword: "false",//默认关闭手势密码
            agreeAgreement: "false", //默认弹出协议,
            userLogin: ""//用户登录成功保存数据
        };
        // 倒计时
        this.countDown = function (second, callback) {
            var time = second;
            var id = null;
            this.countDown.stopCount = function () {
                if (id) {
                    window.clearInterval(id);
                    that.log("countDown", "已停止倒计时！");
                }
            };
            if (time > 0 && !id) {
                id = setInterval(function () {
                    time--;
                    if (callback) {
                        callback({
                            time: time,
                            id: id,
                        });
                    }
                    if (time == 0) {
                        window.clearInterval(id);
                    }
                }, 1000);
            }
        };
        // 可复用的倒计时
        this.COUNTDOWN = function (sec) {
            var time = sec;
            this.start = function (callback, callback2) {
                if (time > 0) {
                    var index = window.setInterval(function () {
                        time--;
                        if (callback) {
                            callback(time);
                        }
                        if (time == 0) {
                            window.clearInterval(index);
                        }
                    }, 1000);
                    this.index = index;
                    if (!this.created) {
                        this.created = true;
                        callback2(index);
                    }
                }
            };
        };
        // 判断文件是否存在
        this.exist = function (file, callback) {
            if (this.fs) {
                this.fs.exist({
                    path: file
                },
                    callback);
            } else {
                callback(null, false);
            }
        };
        // 删除文件
        this.remove = function (file, callback) {
            if (this.fs) {
                this.fs.remove({
                    path: file
                }, callback);
            } else {
                callback(null, false);
            }
        };
        //保存图片或者视屏到相册
        this.saveMediaToAlbum = function (path) {
            api.saveMediaToAlbum({
                path: path
            }, function (ret, err) {
                if (ret && ret.status) {
                    that.toast('保存成功');
                } else {
                    that.toast('保存失败');
                }
            });
        }
        // 获取实名认证校验(处理的相同状态相同弹窗 跳转不同页面)
        this.checkStaus = function (event, callback) {
            var account = that.getAccount();
            if (!account) return
            // code:200,200已实名，602：您的申请还在审核中，请耐心等待，
            // 614：您的实名认证未通过，请前往重新认证，609：您还不是实名会员，请前往验证
            that.ajaxPro({
                url: "member/is-real-apply",
                values: {
                    token: account.token
                },
                openFlower: true
            }, function (ret) {
                var dataCheck = {
                    statusCode: ret.code,
                    statusText: ret.message
                }
                if (dataCheck.statusCode == 609 || dataCheck.statusCode == 614) {
                    var param = {
                        dtype: "dialog29",
                        data: {
                            status: -2,
                            tips: "",
                            event: event
                        }
                    };
                    that.dialog(param);
                } else if (dataCheck.statusCode == 602) {
                    that.toast("亲,你的信息正在审核中……");
                } else if (dataCheck.statusCode == 200) {
                    if (ret.data.status == 1) {
                        // 审核通过
                        callback(dataCheck.statusCode);
                    } else {
                        var param = {
                            dtype: "dialog29",
                            data: {
                                status: -2,
                                tips: "",
                                event: event
                            }
                        };
                        that.dialog(param);
                    }
                } else {
                    var param = {
                        dtype: "dialog29",
                        data: {
                            status: dataCheck.statusCode,
                            tips: dataCheck.statusText,
                            event: event
                        }
                    };
                    that.dialog(param);
                }
            })
        };
        // 获取实名认证校验(处理不同的状态跳转不同页面)
        this.checkStausOther = function (callback) {
            var account = that.getAccount();
            if (!account) return
            // code:200,200已实名，602：您的申请还在审核中，请耐心等待，
            // 614：您的实名认证未通过，请前往重新认证，609：您还不是实名会员，请前往验证
            that.ajaxPro({
                url: "member/is-real-apply",
                values: {
                    token: account.token
                },
                openFlower: true
            }, function (ret) {
                callback(ret)
            })
        };
        //用户是否设置交易密码
        this.isPwd = function (callback) {
            var account = that.getAccount();
            if (!account) return
            that.ajaxPro({
                url: "member/isset-pwd",
                values: {
                    token: account.token
                },
                openFlower: true
            }, function (ret) {
                callback(ret);
            })
        };
        //上传图片
        this.uploadImg = function (imgUrl, callback) {
            var account = that.getAccount();
            if (!account) return
            api.ajax({
                url: that.ajaxUrl + "upload/img",
                method: 'post',
                timeout: 30,
                data: {
                    values: {
                        token: account.token,
                        version: that.inAV
                    },
                    files: {
                        "file": imgUrl
                    }
                },
            }, function (ret, err) {
                that.closeFlower();
                that.log("接口请求返回---------------", that.ajaxUrl + "member/img" + JSON.stringify(ret));
                //ajax错误
                if (err) {
                    var errArr = ["连接错误", "网络超时", "授权错误", "数据类型错误", "不安全的数据"];
                    that.toast(errArr[err.code]);
                    return false
                }
                if (ret) {
                    callback(ret)
                } else {
                    that.toast("网络链接失败!");
                }
            })
        }
        // 获取充值实名校验
        this.rechangChecked = function (isback, callback) {
            var account = that.getAccount();
            if (!account) return
            that.ajaxPro({
                url: "recharge/verify",
                values: {
                    token: account.token
                },
                openFlower: true
            }, function (ret) {
                //1、已实名校验，3、新手未下单，弹提示窗  644  请进行充值校验
                if (isback) { //是否需要回调
                    callback(ret);
                    return false
                }
                if (ret.code == 200) {
                    if (ret.data == 3) {
                        var param = {
                            dtype: "dialog421",
                            data: {
                                event: "YESIKNOW"
                            }
                        };
                        that.dialog(param);
                        return
                    }
                    if (ret.data == 2) {
                        that.toast("正在实名审核中，请通过后再次进行充值");
                        return
                    }
                    if (ret.data == 1) {
                        var cointypecontract = {
                            page: "common/headerwin",
                            name: "littlemoneyrecharge_headerwin",
                            param: {
                                subpage: "extrapage/littlemoneyrecharge",
                                name: "littlemoneyrecharge",
                                title: "充值",
                                allowEdit: true
                            }
                        };
                        var recoinNumber = JSON.stringify(cointypecontract);
                        that.goPushPage(recoinNumber);
                        return
                    }
                } else {
                    var param = {
                        dtype: "dialog42",
                        data: {
                            event: "checkRealName"
                        }
                    };
                    that.dialog(param);
                    that.toast(ret.message);
                }
            })
        };
        //获取用户实名信息
        this.getUserVerify = function (callback) {
            var account = that.getAccount();
            if (!account) return
            that.ajaxPro({
                url: "member/get-userinfo",
                values: {
                    token: account.token
                },
                openFlower: true
            }, function (ret) {
                callback(ret);
            })
        }
        // 获取BHPay关联信息
        this.getBhpayAbout = function (callback) {
            var account = that.getAccount();
            if (!account) return
            that.ajaxPro({
                url: "bhpay/get-card",
                values: {
                    token: account.token
                },
                openFlower: true
            }, function (ret) {
                callback(ret);
            })
        };
        // 截取对应位小数
        this.sliceNum = function (num, digit) {
            var re = new RegExp('([0-9]+\.[0-9]{0,' + digit + '})[0-9]*');
            var thisNum = String(num).replace(re, "$1");
            return thisNum
        }
        //检测是否是网址
        this.regHttp = function (url) {
            var reg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/;//是否是网址的正则
            return reg.test(url)
        }
        // 获取区域码
        this.getAreaCode = function (callback) {
            that.openFlower();
            api.ajax({
                url: that.ajaxUrl + "site/country",
                method: 'post',
                timeout: 30,
                data: {
                    values: {
                        version: that.inAV
                    }
                },
            }, function (ret, err) {
                that.stopRefresh();
                that.closeFlower();
                that.log("接口请求返回---------------", that.ajaxUrl + "site/country" + JSON.stringify(ret));
                //ajax错误
                if (err) {
                    var errArr = ["连接错误", "网络超时", "授权错误", "数据类型错误", "不安全的数据"];
                    that.toast(errArr[err.code]);
                    return false
                }
                if (ret) {
                    callback(ret)
                } else {
                    that.toast("网络链接失败!");
                }
            })
        };

        // 解析json
        this.parse = function (json) {
            this.log("parse", json);
            var result = null;
            if (json && typeof json == "string") {
                result = JSON.parse(json);
            } else {
                result = json;
            }
            return result;
        };
        // 删除偏好设置
        this.rmStorage = function (key) {
            if (key) {
                api.removePrefs({
                    key: key
                });
            }
        };

        // 统一APP入口创建frame
        this.openFrame = function (config) {
            // console.log("****************"+JSON.stringify(config));
            if (config instanceof Object) {
                api.openFrame(config);
            }
        };
        // 把json转为字符串
        this.jsonStr = function (jsonObj) {
            var result;
            if (jsonObj instanceof Array || jsonObj instanceof Object) {
                result = JSON.stringify(jsonObj);
            }
            return result;
        };
        // 关闭当前窗口
        this.closeW = function (name) {
            if (!name) {
                api.closeWin();
            } else {
                api.closeWin({
                    name: name
                });
            }
            this.setStorage("curWin", "");
            this.setStorage("leftW", name);
        };
        // 创建底部tab栏
        this.createBottomTab = function () {
            // 创建底部tab
            api.openFrame({
                name: "tab",
                url: that.hd + "toolhtml/tab_win.html",
                bgColor: "#ffffff",
                rect: {
                    x: 0,
                    y: that.H - that.btH,
                    w: that.W,
                    h: that.btH,
                    marginBottom: 0
                }
            });
        };
        //切换主页(原生组件)
        this.setTabBarAttr = function (pageNum) {
            api.setTabBarAttr({
                index: pageNum
            });
        };
        //监听原生导航栏点击
        this.headerMap = function (rightCallback) {
            that.listen("navitembtn", function (ret) {
                var pageValue = api.pageParam;
                if (ret.type == "left") {
                    that.navigationBarClickLeft(pageValue.pageName);
                }
                if (ret.type == "right") {
                    var rightParams = pageValue.rightParam || '';
                    rightCallback(rightParams);
                }
            });
        };

        //公用导航栏(原生组件)
        this.setNavBarAttr = function (pageValue) {
            var param = {
                name: pageValue.name,
                url: that.hd + pageValue.subpage + ".html",
                bgColor: pageValue.bgColor || '#fff',
                fontSize: "17",
                title: pageValue.title,
                allowEdit: pageValue.allowEdit || false,
                navigationBar: {
                    background: pageValue.bgColor || '#fff',
                    leftButtons: [{
                        color: "#ffd203",
                        fontSize: "17",
                        fontWeight: "normal",
                        iconPath: that.rd + "/image/leftrtret.png",
                    }]
                },
                pageParam: pageValue.param
            }
            if (pageValue.isRightUrl && pageValue.isRightUrl == true) {
                param.url = pageValue.subpage;
            }
            if (pageValue.rightTitle) {
                param.navigationBar.rightButtons = [{
                    text: pageValue.rightIconUrl ? "" : pageValue.rightTitle,
                    color: "#898989",
                    fontSize: "14",
                    fontWeight: "normal",
                    iconPath: pageValue.rightIconUrl ? that.rd + pageValue.rightIconUrl : ""
                }]
            }
            that.log("-----------------页面路由-------------" + param.url);
            that.log("=================页面参数=============" + JSON.stringify(param.pageParam));
            api.openTabLayout(param);
        }
        //调用默认组件
        this.setNavBarAttrPrimary = function (pageValue) {
            var param = {
                name: pageValue.name,
                url: pageValue.url,
                bgColor: '#fff',
                fontSize: "17",
                title: pageValue.title,
                navigationBar: {},
                pageParam: pageValue.param || ""
            }
            api.openTabLayout(param);
        }
        //公共判断原生组件方法
        this.navigationBarClickLeft = function (value, toWinName) {
            if (toWinName) {
                that.toWin(toWinName);
                return
            }
            that.closeW(value);
        }
        //判断空对象
        this.isNullObj = function (obj) {
            if (obj instanceof Array || obj instanceof Object) {
                result = JSON.stringify(obj);
                var name;
                for (name in obj) {
                    return false;
                }
                return true;
            }
        };
        // 创建主要界面
        this.createMain = function (name, reload) {
            var url = that.hd + "mainpage/" + name + ".html";
            var mainMarginBt = that.btH; // 61
            if (that.isiPhone10) {
                mainMarginBt = 80;
            }
            var frameRect = {
                x: 0,
                y: that.hH,
                w: that.W,
                h: that.H - that.hH - mainMarginBt,
                marginBottom: mainMarginBt
            };
            if (this.deviceModel.toLowerCase().indexOf("OPPO") != -1) {
                frameRect = {
                    x: 0,
                    y: that.hH,
                    w: that.W,
                    h: that.H - that.hH - mainMarginBt - 10
                };
            };
            if (name == "orinpage") {
                var $y = that.hH + that.accMul(2.2, that.htmlFs) + 10;
                frameRect.y = $y;
                frameRect.h = 'auto';
            }
            api.openFrame({
                name: name,
                url: url,
                rect: frameRect,
                reload: reload ? reload : false,
                bgColor: "#f5f5f5"
            });
        };
        // 打开弹窗frame
        this.dialog = function (param) {
            that.log("弹窗数据+++++++++++++++", param)
            that.openFrame({
                name: "dialog",
                url: that.hd + "common/dialog.html",
                bgColor: "rgba(0,0,0,0.4)",
                rect: {
                    x: 0,
                    y: 0,
                    w: that.W,
                    h: "auto"
                },
                pageParam: param
            });
        };
        // 显示页面
        this.showFrame = function (name) {
            that.log("调用showFrame++++++++++++++" + name);
            api.setFrameAttr({
                name: name,
                hidden: false
            });
        };
        // 统一处理点击跳转页面
        this.handlePage = function () {
            var account = that.getAccount();
            this.log("handlePage", "调用了handlePage");
            $(".go-page").unbind("click");
            $(".go-page").click(function () {
                // 判断是否终止跳转
                if ($(this).data("defeat")) {
                    var msg = that.parse($(this).data("defeat")).msg;
                    that.toast(msg);
                    return;
                }

                var p = that.parse($(this).data("param"));
                // that.log("获取传入阐述+++++++++++++");
                var sp = p.param;
                if (p.name) {
                    if (sp) {
                        sp.winName = p.name;
                    }
                } else {
                    if (sp) {
                        sp.winName == "";
                    }
                }
                if (sp && sp.name) {
                    sp.frameName = sp.name;
                }
                if (sp && !sp.name) {
                    sp.frameName = "";
                }
                // 是否要判断账号里的字段
                if (p.checkAccount) {
                    var ispass = true;
                    for (var key in p.checkAccount) {
                        if (p.checkAccount[key] != account[key]) {
                            ispass = false;
                        }
                    }
                    if (!ispass) {
                        sp = p.param2;
                    }
                }
                var conf = {
                    name: p.name,
                    url: that.hd + p.page + ".html",
                    pageParam: sp
                };

                // 判断是否允许编辑
                if (p.allowEdit && p.allowEdit == "true") {
                    conf.allowEdit = true;
                }

                // 判断是否可以滑动返回（iOS有效）
                if (p.slideBack && p.slideBack == "false") {
                    conf.slidBackEnabled = false;
                }
                that.log("config参数参数+++++++++++", conf);
                if (p.needLogin && !that.isLogin()) {
                    that.goLogin();
                    return;
                } else {
                    that.openWin(conf);
                }
            });
        };
        //点击跳转页面
        this.goPushPage = function (recoinNumber) {
            // 判断是否终止跳转
            var p = that.parse(recoinNumber);
            // that.log("获取传入阐述+++++++++++++");
            var sp = p.param;
            if (p.name) {
                if (sp) {
                    sp.winName = p.name;
                }
            } else {
                if (sp) {
                    sp.winName == "";
                }
            }
            if (sp && sp.name) {
                sp.frameName = sp.name;
            }
            if (sp && !sp.name) {
                sp.frameName = "";
            }
            // 是否要判断账号里的字段
            if (p.checkAccount) {
                var ispass = true;
                for (var key in p.checkAccount) {
                    if (p.checkAccount[key] != account[key]) {
                        ispass = false;
                    }
                }
                if (!ispass) {
                    sp = p.param2;
                }
            }
            var conf = {
                name: p.name,
                url: that.hd + p.page + ".html",
                pageParam: sp
            };

            // 判断是否允许编辑
            if (p.allowEdit && p.allowEdit == "true") {
                conf.allowEdit = true;
            }

            // 判断是否可以滑动返回（iOS有效）
            if (p.slideBack && p.slideBack == "false") {
                conf.slidBackEnabled = false;
            }
            that.log("config参数参数+++++++++++", conf);
            if (p.needLogin && !that.isLogin()) {
                that.goLogin();
                return;
            } else {
                that.openWin(conf);
            }
        };
        // 隐藏页面
        this.hideFrame = function (name) {
            api.setFrameAttr({
                name: name,
                hidden: true
            });
        };
        this.toWin = function (name) {
            api.closeToWin({
                name: name
            });
            this.setStorage("curWin", name);
        };
        // 关闭到主窗口
        this.toMainWin = function () {
            api.closeToWin({
                name: "root"
            });
            this.setStorage("curWin", "root");
            this.setStorage("leftW", "login");
        };
        // 关闭对话框frame
        this.closeDialog = function () {
            api.closeFrame({
                name: "dialog"
            });
        };
        // 检查登录
        this.isLogin = function () {
            var isNewAPP = that.getSyncStorage("isNewAPP");
            if (!isNewAPP) return false
            var accountStr = that.parse(that.getSyncStorage("account"));
            if (accountStr.userLogin == "" || !accountStr) return false
            return true
        };
        // 获取账号
        this.getAccount = function () {
            var accountStr = that.parse(that.getSyncStorage("account"));
            if (accountStr.userLogin == "") return false
            var accturn = that.parse(accountStr.userLogin);
            return accturn
        };
        // 获取用户默认设置
        this.getAccountSet = function () {
            return that.parse(that.getSyncStorage("account"))
        };
        // 保存账号
        this.setAccount = function (account) {
            that.setStorage("account", account);
        };
        //请求BHPay授权
        this.getBhpayURL = function (account, callback) {
            that.ajaxPro({
                url: "bhpay/home",
                values: {
                    token: account.token
                },
                openFlower: true
            }, function (ret) {
                callback(ret);
            })
        };
        // 获取服务器上app的最新版本，用于强制升级（只对android有效）
        this.checkAppVer = function (callback) {
            var values = {};
            var account = that.getAccount();
            if (account) {
                values.token = account.token;
            }
            values.system = that.ST;
            values.deviceModel = that.deviceModel
            values.app_code = that.FG + "_" + that.ST;
            that.ajax({
                param: {
                    method: "post",
                    url: that.ajaxUrl + "site/open",
                    data: {
                        values: values
                    },
                    callback: function (ret, err) {
                        // alert(JSON.stringify(ret));
                        that.log("checkAppVer", "返回：" + JSON.stringify(ret));
                        callback(ret, err);
                    }
                },
                extra: {
                    isflower: false
                }
            });
        };
        //请求用户资产
        this.getProperties = function (account, callback, flower) {
            if (!account) return
            that.ajaxPro({
                url: "finance/show-assets-lists",
                values: {
                    token: account.token
                },
                openFlower: true
            }, function (ret) {
                callback(ret);
            })
        };
        //请求用户特定资产(BCNY,CNY,USDT)
        this.specialCoin = function (account, callback) {
            if (!account) return
            that.ajaxPro({
                url: "finance/search-special-coin",
                values: {
                    token: account.token
                },
                openFlower: true
            }, function (ret) {
                callback(ret);
            })
        };
        // 打开手机自带浏览器
        this.openSysNavi = function (url, callback) {
            if (url) {
                if (that.ST == "android") {
                    api.openApp({
                        androidPkg: "android.intent.action.VIEW",
                        uri: url
                    }, function (ret, err) {
                        if (callback) {
                            callback(ret, err);
                        }
                    });
                } else {
                    api.openApp({
                        iosUrl: url
                    }, function (ret, err) {
                        if (callback) {
                            callback(ret, err);
                        }
                    });
                }
            } else {
                that.toast("无效地址");
            }
        };
        // 初始化点击返回
        if ($(".aui-pull-left")) {
            $(".aui-pull-left").unbind("click").on("click", function () {
                var type = $(".aui-pull-left").data("type");
                var gobackPage = $(this).attr("data-chooseBack");
                that.log("界面类型type界面类型type界面类型type界面类型type+++++++++", type);
                if (type == "frame") {
                    api.closeFrame();
                }
                if (type == "win" && gobackPage) {
                    that.trigger("goMain");
                    return
                }
                if (type == "win") {
                    api.closeWin();
                    that.setStorage("curWin", "");
                }

            });
        }
        // 统一处理点击跳转页面
        this.handlePage = function () {
            var account = that.getAccount();
            that.log("handlePage", "调用了handlePage");
            $(".go-page").unbind("click");
            $(".go-page").click(function () {
                // 判断是否终止跳转
                if ($(this).data("defeat")) {
                    var msg = that.parse($(this).data("defeat")).msg;
                    that.toast(msg);
                    return;
                }

                var p = that.parse($(this).data("param"));
                // that.log("获取传入阐述+++++++++++++");
                var sp = p.param;
                if (p.name) {
                    if (sp) {
                        sp.winName = p.name;
                    }
                } else {
                    if (sp) {
                        sp.winName == "";
                    }
                }
                if (sp && sp.name) {
                    sp.frameName = sp.name;
                }
                if (sp && !sp.name) {
                    sp.frameName = "";
                }
                // 是否要判断账号里的字段
                if (p.checkAccount) {
                    var ispass = true;
                    for (var key in p.checkAccount) {
                        if (p.checkAccount[key] != account[key]) {
                            ispass = false;
                        }
                    }
                    if (!ispass) {
                        sp = p.param2;
                    }
                }
                var conf = {
                    name: p.name,
                    url: that.hd + p.page + ".html",
                    pageParam: sp
                };

                // 判断是否允许编辑
                if (p.allowEdit && p.allowEdit == "true") {
                    conf.allowEdit = true;
                }

                // 判断是否可以滑动返回（iOS有效）
                if (p.slideBack && p.slideBack == "false") {
                    conf.slidBackEnabled = false;
                }
                that.log("config参数参数+++++++++++", conf);
                if (p.needLogin && !that.isLogin()) {
                    that.goLogin();
                    return;
                } else {
                    that.openWin(conf);
                }
            });
        };
        //伪数组对象转数组
        this.toArr = function (obj) {
            var arrayNew = [];
            for (var key in obj) {
                var thisValue = {
                    keys: key,
                    value: obj[key]
                }
                arrayNew.push(thisValue);
            }
            arrayNew.sort(function (a, b) {
                return a.keys < b.keys
            })
            return arrayNew
        }
        //转化时间为天 时分秒
        this.getDuration = function (my_time) {
            var my_time = my_time;
            var days = my_time / 60 / 60 / 24;
            var daysRound = Math.floor(days) < 10 ? ("0" + Math.floor(days)) : Math.floor(days);
            var hours = my_time / 60 / 60 - (24 * daysRound);
            var hoursRound = Math.floor(hours) < 10 ? ("0" + Math.floor(hours)) : Math.floor(hours);
            var minutes = my_time / 60 - (24 * 60 * daysRound) - (60 * hoursRound);
            var minutesRound = Math.floor(minutes) < 10 ? ("0" + Math.floor(minutes)) : Math.floor(minutes);
            var seconds = my_time - (24 * 60 * 60 * daysRound) - (60 * 60 * hoursRound) - (60 * minutesRound);
            if (seconds < 10) {
                seconds = "0" + seconds
            }
            // console.log('转换时间:', daysRound + '天', hoursRound + '时', minutesRound + '分', seconds + '秒');
            if (Number(daysRound) > 10) {
                time = daysRound + "天" + ':' + hoursRound + "时";
                if (hoursRound == 0) {
                    time = daysRound - 1 + "天" + ":" + 23 + "时";
                }
            }
            if (1 <= Number(daysRound) <= 10) {
                time = daysRound + "天" + ':' + hoursRound + "时" + ':' + minutesRound + "分";
                if (Number(minutesRound) == 0) {
                    time = daysRound + "天" + ':' + hoursRound + "时" + ':' + "01" + "分";
                }
                if (Number(hoursRound) == 0 && Number(minutesRound) == 0 && Number(daysRound) > 2) {
                    time = daysRound - 1 + "天" + ":" + 23 + "时" + ":" + 59 + "分";
                    if (Number(daysRound) == 1) {
                        time = 0 + "天" + ":" + 23 + "时" + ":" + 59 + "分";
                    }
                }
            }
            if (Number(daysRound) < 1) {
                time = hoursRound + "时" + ':' + minutesRound + "分" + ":" + seconds + "秒";
            }
            return time;
        };
        //转化时间为天 时分秒(不包含文字(天 时 分 ))
        this.getDurationNew = function (my_time) {
            var my_time = my_time;
            var days = my_time / 60 / 60 / 24;
            var daysRound = Math.floor(days) < 10 ? ("0" + Math.floor(days)) : Math.floor(days);
            var hours = my_time / 60 / 60 - (24 * daysRound);
            var hoursRound = Math.floor(hours) < 10 ? ("0" + Math.floor(hours)) : Math.floor(hours);
            var minutes = my_time / 60 - (24 * 60 * daysRound) - (60 * hoursRound);
            var minutesRound = Math.floor(minutes) < 10 ? ("0" + Math.floor(minutes)) : Math.floor(minutes);
            if (Number(daysRound) > 10) {
                time = daysRound + ':' + hoursRound;
                if (hoursRound == 0) {
                    time = daysRound - 1 + ":" + 23;
                }
            }
            if (1 <= Number(daysRound) <= 10) {
                time = daysRound + ':' + hoursRound + ':' + minutesRound;
                if (Number(minutesRound) == 0) {
                    time = daysRound + ':' + hoursRound + ':' + "01";
                }
                if (Number(hoursRound) == 0 && Number(minutesRound) == 0 && Number(daysRound) > 2) {
                    time = daysRound - 1 + ":" + 23 + ":" + 59;
                    if (Number(daysRound) == 1) {
                        time = 0 + ":" + 23 + ":" + 59;
                    }
                }
            }
            if (Number(daysRound) < 1) {
                time = "00" + ":" + hoursRound + ':' + minutesRound;
            }
            return time;
        };
        this.showdateArr = function (m, n) {
            var uom = new Date(m - 0 + n * 86400000);
            var month = uom.getMonth() + 1 < 10 ? "0" + (uom.getMonth() + 1) : uom.getMonth() + 1;
            var days = uom.getDate() < 10 ? "0" + uom.getDate() : uom.getDate();
            var hh = uom.getHours() < 10 ? "0" + uom.getHours() : uom.getHours();
            var mm = uom.getMinutes() < 10 ? "0" + uom.getMinutes() : uom.getMinutes();
            var ss = uom.getSeconds() < 10 ? "0" + uom.getSeconds() : uom.getSeconds();
            uom = uom.getFullYear() + "-" + month + "-" + days + " " + hh + ":" + mm + ":" + ss;
            return uom;
        };
        //获取指定时间到指定时间的天数
        this.DateDiff2 = function (sDate1, sDate2) {
            sDate1 = sDate1.split(' ')[0];
            sDate2 = sDate2.split(' ')[0];
            var aDate, oDate1, oDate2, iDays;
            aDate = sDate1.split("-");
            oDate1 = new Date(aDate[0], aDate[1], aDate[2]);
            aDate = sDate2.split("-");
            oDate2 = new Date(aDate[0], aDate[1], aDate[2]);
            iDays = parseInt((oDate1 - oDate2) / 1000 / 60 / 60 / 24);
            return Math.abs(iDays)
        };
        //获取当前日期指定前几天或者后几天的日期(不包括年)
        this.getBeforeNoYear = function (strDate, n) { //strDate 为字符串日期 如:'2019-01-01' n为你要传入的参数，当前为0，前一天为-1，后一天为1
            var datt = strDate.split('-'); //这边给定一个特定时间
            var newDate = new Date(datt[0], datt[1] - 1, datt[2]);
            var befminuts = newDate.getTime() + 1000 * 60 * 60 * 24 * parseInt(n); //计算前几天用减，计算后几天用加，最后一个就是多少天的数量
            var beforeDat = new Date;
            beforeDat.setTime(befminuts);
            var befMonth = beforeDat.getMonth() + 1;
            var mon = befMonth >= 10 ? befMonth : '0' + befMonth;
            var befDate = beforeDat.getDate();
            var da = befDate >= 10 ? befDate : '0' + befDate;
            var newDate = mon + '月' + da + "日";
            return newDate;
        };
        // 获取当前日期的时间戳（单位是s）
        this.getCurStamp = function () {
            var mili = new Date().getTime();
            return mili / 1000;
        };
        // 转换yyyy-mm-dd hh:mm:ss格式为秒
        this.toSecond = function (date) {
            var first = date.split(" ")[0];
            var second = date.split(" ")[1];
            var splits1 = first.split("-");
            var splits2 = second.split(":");
            var result = new Date(parseInt(splits1[0]), parseInt(splits1[1]) - 1, parseInt(splits1[2]), parseInt(splits2[0]), parseInt(splits2[1]), parseInt(splits2[2])).getTime();
            return result / 1000;
        };
        //检查是否装某款APP
        this.IsInsatallApp = function (iosName, androidName, callback) {
            if (that.ST == "ios") {
                api.appInstalled({
                    sync: false,
                    appBundle: iosName
                }, function (ret, err) {
                    callback(ret.installed)
                })
            } else {
                api.appInstalled({
                    sync: false,
                    appBundle: androidName
                }, function (ret, err) {
                    callback(ret.installed)
                })
            }
        }
        // 可复用的倒计时
        this.COUNTDOWN = function (sec) {
            var time = sec;
            this.start = function (callback, callback2) {
                if (time > 0) {
                    var index = window.setInterval(function () {
                        time--;
                        if (callback) {
                            callback(time);
                        }
                        if (time == 0) {
                            window.clearInterval(index);
                        }
                    }, 1000);
                    this.index = index;
                    if (!this.created) {
                        this.created = true;
                        callback2(index);
                    }
                }
            };
        };
        // 异步读取偏好设置
        this.getAsyncStorage = function (key, callback) {
            if (key) {
                api.getPrefs({
                    key: key
                }, function (ret, err) {
                    if (callback) {
                        callback(JSON.parse(ret.value));
                    }
                });
            } else {
                if (callback) {
                    callback(null);
                }
            }
        };
        // 下载文件
        this.download = function (url, callback) {
            if (url) {
                var arr = url.split("/");
                var fileName = arr[arr.length - 1];
                api.download({
                    url: url,
                    savePath: "fs://renDown/" + fileName,
                    report: true,
                    cache: true,
                    allowResume: true
                }, function (ret, err) {
                    if (ret.state != 1) {
                        if (ret.state == 2) {
                            that.log("download", "下载文件失败：" + url);
                        } else {
                            that.log("download", "文件下载中");
                        }
                    }
                    if (callback) {
                        callback(ret, err);
                    }
                });
            }
        };
        this.downloadImg = function (url, name, callback) {
            if (url) {
                if (name) {
                    fileName = name;
                }
                api.download({
                    url: url,
                    savePath: "fs://newshargeimg/" + fileName + ".png",
                    report: true,
                    cache: true,
                    allowResume: true
                }, function (ret, err) {
                    if (ret.state == 1) {
                        callback(ret);
                    } else {
                        that.log("=====下载错误信息", err);
                    }
                });
            }
        };
        this.download2 = function (url, name, callback) {
            if (url) {
                var arr = url.split("/");
                var fileName = arr[arr.length - 1];
                var fileFix = fileName.split(".")[1];
                if (name) {
                    fileName = name;
                }
                api.download({
                    url: url,
                    savePath: "fs://renDown/" + fileName + ".jpg",
                    report: true,
                    cache: true,
                    allowResume: true
                }, function (ret, err) {
                    if (ret.state != 1) {
                        if (ret.state == 2) {
                            that.log("download", "下载文件失败：" + url);
                        } else {
                            that.log("download", "文件下载中");
                        }
                    }
                    if (callback) {
                        callback(ret, err);
                    }
                });
            }
        };
        //请求对应的权限
        this.getCamera = function (power, callback) {
            var arrPower = [];
            arrPower.push(power);
            api.requestPermission({
                list: arrPower,
                code: 1
            }, function (ret, err) {
                callback(ret)
            });
        }
        // 拍照
        this.shootPic = function (callback) {
            var isNeverOpen = that.getSyncStorage("isNeverOpen");//获取是否永久不提示获取权限
            var cameraList = api.hasPermission({
                list: ['camera']
            });
            if (cameraList[0].granted == false) {
                if (isNeverOpen && isNeverOpen == "false") return false  //用户选择不给权限并不提醒
                that.getCamera("camera", function (ret) {
                    var retData = ret;
                    if (retData.never && retData.never == true && that.ST != "ios") {
                        that.setStorage("isNeverOpen", "false");
                        return false
                    }
                    if (retData.list[0].granted == true) {
                        that.trigger("openCamera");
                    }
                });
            } else {
                api.getPicture({
                    sourceType: "camera",
                    mediaValue: "pic",
                    encodingType: "jpg",
                    destinationType: "url",
                    allowEdit: false,
                    quality: 100,
                    saveToPhotoAlbum: false
                }, callback);
            }
            that.listen("openCamera", function () {
                api.getPicture({
                    sourceType: "camera",
                    mediaValue: "pic",
                    encodingType: "jpg",
                    destinationType: "url",
                    allowEdit: false,
                    quality: 100,
                    saveToPhotoAlbum: false
                }, callback);
            })
        };
        // 相册选择
        this.getPic = function (callback) {
            var isNeverOpenPhoto = that.getSyncStorage("isNeverOpenPhoto");//获取是否永久不提示获取权限
            var cameraList = api.hasPermission({
                list: ['photos']
            });
            if (cameraList[0].granted == false) {
                if (isNeverOpenPhoto && isNeverOpenPhoto == "false") return false  //用户选择不给权限并不提醒
                that.getCamera("photos", function (ret) {
                    var retData = ret;
                    if (retData.never && retData.never == true && that.ST != "ios") {
                        that.setStorage("isNeverOpenPhoto", "false");
                        return false
                    }
                    if (retData.list[0].granted == true) {
                        that.trigger("openPhoto");
                    }
                });
            } else {
                api.getPicture({
                    sourceType: "library",
                    mediaValue: "pic",
                    encodingType: "jpg",
                    destinationType: "url",
                    allowEdit: false,
                    quality: 100,
                    saveToPhotoAlbum: false
                }, callback);
            }
            that.listen("openPhoto", function () {
                api.getPicture({
                    sourceType: "library",
                    mediaValue: "pic",
                    encodingType: "jpg",
                    destinationType: "url",
                    allowEdit: false,
                    quality: 100,
                    saveToPhotoAlbum: false
                }, callback);
            })

        };
        // 相册选择
        this.getPicJurisdiction = function (callback) {
            var isNeverOpenPhotonew = that.getSyncStorage("isNeverOpenPhotonew");//获取是否永久不提示获取权限
            var cameraList = api.hasPermission({
                list: ['photos']
            });
            if (cameraList[0].granted == false) {
                if (isNeverOpenPhotonew && isNeverOpenPhotonew == "false") return false  //用户选择不给权限并不提醒
                that.getCamera("photos", function (ret) {
                    var retData = ret;
                    if (retData.never && retData.never == true && that.ST != "ios") {
                        that.setStorage("isNeverOpenPhotonew", "false");
                        return false
                    }
                    if (retData.list[0].granted == true) {
                        callback(true)
                    }
                });
            } else {
                callback(true)
            }
        };
        //图片转base64
        this.imgToTrans = function (imgPath, callback) {
            var trans = api.require("trans");
            trans.decodeImgToBase64({
                imgPath: imgPath
            }, function (ret, err) {
                if (ret.status) {
                    callback(ret.base64Str);
                } else {
                    that.log("trans", err);
                }
            })
        }
        // 打开下载
        this.openloadframe = function (param) {
            this.log("弹窗数据+++++++++++++++", param)
            this.openFrame({
                name: "downloadApk",
                url: that.hd + "common/download.html",
                bgColor: "rgba(0,0,0,0.4)",
                rect: {
                    x: 0,
                    y: 0,
                    w: that.W,
                    h: "auto"
                },
                pageParam: param
            });
            this.toFront("downloadApk");
        };
        // 封装actionSheet
        this.sheet = function (config, callback) {
            api.actionSheet(config, function (ret, err) {
                callback(ret, err);
            });
        };
        this.VSLIDER = function (conf, callback) {
            // 公用this
            var THIS = this;
            // 容器高度
            this.itemH = $(conf.ele + " .slider-item").height();
            // relative定位的当前top值
            this.curTop;
            // 轮播项数
            this.count;
            // 当前轮播项索引，从0开始计数
            this.curIndex;

            // 定时器的id
            THIS.vindex;

            // 初始化数据
            this.init = function (count) {
                this.curTop = 0;
                this.curIndex = 0;
                this.count = $(conf.ele + " .slider-item").length;
                callback({
                    curTop: THIS.curTop,
                    curIndex: THIS.curIndex,
                    count: THIS.count
                });
            };
            // 心跳任务
            this.theart = function (milli, callback) {
                if (milli) {
                    // console.log("milli" + milli + "callback" + callback);
                    THIS.vindex = window.setInterval(callback, milli);
                    this.theart.stop = function () {
                        window.clearInterval(index);
                    };
                }
            };
            // 初始化数据
            this.init();
            // 开始定时轮播
            this.theart(conf.interval + conf.animateInter, function () {
                // that.log("vslider_timer","定时轮播");
                // ("定时轮播");
                THIS.curTop -= THIS.itemH;
                $(".v-slider > .slider-w").animate({
                    top: THIS.curTop + "px"
                }, conf.animateInter, "linear", function () {
                    var pastItemCopy = $("#" + THIS.curIndex).clone(true);
                    $("#" + THIS.curIndex).remove();
                    THIS.curTop += THIS.itemH;
                    $(".slider-w")
                        .css({
                            top: THIS.curTop + "px"
                        })
                        .append(pastItemCopy);
                    THIS.curIndex++;
                    if (THIS.curIndex >= THIS.count) {
                        THIS.curIndex = 0;
                    }
                    callback({
                        curTop: THIS.curTop,
                        curIndex: THIS.curIndex,
                        count: THIS.count
                    });
                });
            });

        };
        //判断年龄
        this.getAge = function (UUserCard, num) {
            if (num == 1) {
                //获取出生日期
                birth = UUserCard.substring(6, 10) + "-" + UUserCard.substring(10, 12) + "-" + UUserCard.substring(12, 14);
                return birth;
            }
            if (num == 2) {
                //获取性别
                if (parseInt(UUserCard.substr(16, 1)) % 2 == 1) {
                    //男
                    return "男";
                } else {
                    //女
                    return "女";
                }
            }
            if (num == 3) {
                //获取年龄
                var myDate = new Date();
                var month = myDate.getMonth() + 1;
                var day = myDate.getDate();
                var age = myDate.getFullYear() - UUserCard.substring(6, 10) - 1;
                if (UUserCard.substring(10, 12) < month || UUserCard.substring(10, 12) == month && UUserCard.substring(12, 14) <= day) {
                    age++;
                }
                return age;
            }
        }
        // 打开图片处理界面
        this.openImgHandle = function (param) {
            this.openWin({
                name: "imagehandle",
                url: this.hd + "common/imagehandle.html",
                pageParam: param
            });
        };
        // 初始化裁剪模块
        this.initClipper = function (param, callback) {
            if (this.clipper && param && param.srcPath) {
                this.clipper.open(param, function (ret, err) {
                    if (err) {
                        that.log("initClipper", "初始化clipper失败");
                        callback(null, err);
                        return;
                    }
                    if (ret) {
                        that.log("initClipper", ret);
                        callback(ret, null);
                    }
                });
            }
        };
        // 图片裁剪函数
        this.cutImg = function (param, callback) {
            if (this.clipper && param.destPath) {
                that.log("param++++++++++++++++++++++++++++", param)
                this.clipper.save(param, function (ret, err) {
                    if (err) {
                        that.log("cutImg_err", err);
                        if (callback) {
                            callback(null, err);
                        }
                        return;
                    }
                    if (ret) {
                        that.log("cutImg", ret);
                        if (callback) {
                            callback(ret, null);
                        }
                    }
                });
            }
        };
        // 图片压缩
        this.compImg = function (shareImage, callback) {
            // alert("查看参数" + JSON.stringify(shareImage));
            if (that.filter && shareImage && shareImage.img) {
                that.filter.compress(shareImage, function (ret, err) {
                    // alert("调用方法" + JSON.stringify(ret) + "***" + JSON.stringify(err))
                    if (err) {
                        // alert("===="+JSON.stringify(err));
                        that.log("compImg_err", err);
                        if (callback) {
                            callback(null, err);
                        }
                    }
                    if (ret) {
                        that.log("compImg", ret);
                        if (callback) {
                            callback(ret, null);
                        }
                    }
                });
            }
        };
        // 获取文件名
        this.getFileName = function (filePath) {
            var result = null;
            if (filePath) {
                var pathArr = filePath.split("/");
                result = pathArr[pathArr.length - 1];
            }
            return result;
        };
        // 文件上传接口（支持多文件）
        this.upload = function (conf) {
            // 请求状态码
            var needLogin = -100;
            var ok = 1;
            var fail = 0;
            var accountErr = -1;
            var errArr = ["连接错误", "网络超时", "授权错误", "数据类型错误", "不安全的数据"];
            if (conf && conf instanceof Object) {
                // 开始转菊花
                if (conf.extra.isflower) {
                    if (conf.extra.flowerParam) {
                        if (conf.extra.flowerParam.delay) {
                            that.tout(conf.extra.flowerParam.delay, function () {
                                that.flower(conf.extra.flowerParam);
                            });
                        }
                    } else {
                        that.flower();
                    }
                }
                conf.param.timeout = 15;
                conf.param.data.values['version'] = that.inAV;
                api.ajax(conf.param, function (ret, err) {
                    that.log("--------------返回------------------", JSON.stringify(conf.param))
                    // 关闭菊花
                    if (conf.extra && conf.extra.isflower) {
                        if (that.flower.close) {
                            that.flower.close();
                        }
                        if (conf.extra.flowerParam && conf.extra.flowerParam.delay) {
                            that.tout(conf.extra.flowerParam.delay + 800, function () {
                                that.flower.close();
                            });
                        }
                    }
                    if (ret) {
                        that.log("upload", ret);
                        if (ret.message) {
                            that.toast(ret.message);
                        }
                        if (ret.code == needLogin) {
                            // 跳转到登录界面
                            that.goLogin();
                            return;
                        }
                        if (conf.param.callback) {
                            conf.param.callback(ret, err);
                        }
                    }
                    else {

                        that.toast(errArr[err.code]);
                        api.closeFrame({
                            name: "flower"
                        });
                    }
                });
            }
        };
        // 获取日期（返回格式：yy-mm-dd hh:mm:ss）
        this.getDate = function (stamp, ismili) {
            var date = new Date();
            if (stamp) {
                if (ismili) {
                    date = new Date(stamp);
                } else {
                    date = new Date(stamp * 1000);
                }
            }
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            if (month < 10) {
                month = "0" + month;
            }
            var day = date.getDate();
            if (day < 10) {
                day = "0" + day;
            }
            var hour = date.getHours();
            if (hour < 10) {
                hour = "0" + hour;
            }
            var minute = date.getMinutes();
            if (minute < 10) {
                minute = "0" + minute;
            }
            var second = date.getSeconds();
            if (second < 10) {
                second = "0" + second;
            }
            var final =
                year +
                "-" +
                month +
                "-" +
                day +
                " " +
                hour +
                ":" +
                minute +
                ":" +
                second;
            return final;
        };
    };
    window.APP = toolFun;
    // window.app = new toolFun;
})();
